package com.yiyuan.app.service.impl;

import com.guaike.core.entity.param.Page;
import com.guaike.core.entity.result.PageEntity;
import com.guaike.core.entity.result.Result;
import com.guaike.core.redis.context.ApiContext;
import com.yiyuan.app.config.MyAppConfig;
import com.yiyuan.app.dao.DDetailsPineconeDAO;
import com.yiyuan.app.dao.MConfPrizeDAO;
import com.yiyuan.app.dao.UAppUserDAO;
import com.yiyuan.app.dao.UAppUserEquityDAO;
import com.yiyuan.app.entity.enums.DetailsTypeEnum;
import com.yiyuan.app.entity.enums.LabelTypeEnum;
import com.yiyuan.app.entity.enums.PrizeActionEnum;
import com.yiyuan.app.entity.param.AcceptInviteDTO;
import com.yiyuan.app.entity.po.DDetailsPineconePO;
import com.yiyuan.app.entity.po.MConfPrizePO;
import com.yiyuan.app.entity.po.UAppUserPO;
import com.yiyuan.app.entity.result.AppUser;
import com.yiyuan.app.entity.result.InviteRecordVO;
import com.yiyuan.app.entity.result.InviteVO;
import com.yiyuan.app.service.BaseUtilService;
import com.yiyuan.app.service.InviteService;
import com.yiyuan.app.utils.ImageUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.IOException;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Slf4j
@Service
@AllArgsConstructor
public class InviteServiceImpl implements InviteService {
    private final UAppUserDAO uAppUserDAO;
    private final MConfPrizeDAO mConfPrizeDAO;
    private final BaseUtilService baseUtilService;
    private final DDetailsPineconeDAO dDetailsPineconeDAO;
    private final UAppUserEquityDAO uAppUserEquityDAO;
    private final MyAppConfig myAppConfig;

    @Override
    public Result<InviteVO> myInviteConfig() {
        AppUser currentUser = ApiContext.getCurrentUser();
        UAppUserPO userPO = uAppUserDAO.findById(currentUser.getUserId());
        InviteVO vo = new InviteVO();
        vo.setInviterCode(userPO.getInviterCode());
        if (Objects.nonNull(userPO.getInviterId())) {
            UAppUserPO inviter = uAppUserDAO.findById(currentUser.getUserId());
            vo.setMyInviter(inviter.getNickname());
        }
        if (baseUtilService.checkInvite()) {
            MConfPrizePO prizePO = mConfPrizeDAO.findOne(MConfPrizePO::getAction, PrizeActionEnum.invite.getCode());
            vo.setInvitationPinecone(prizePO.getInvitationPinecone());
            vo.setInvitedPinecone(prizePO.getInvitedPinecone());
        }
        return Result.success().data(vo).build();
    }

    @Override
    public Result<PageEntity<InviteRecordVO>> myInvitePage(Page param) {
        AppUser currentUser = ApiContext.getCurrentUser();
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<DDetailsPineconePO> poPage = dDetailsPineconeDAO.findPageByLabelType(currentUser.getUserId(), LabelTypeEnum.invite_friends.getCode(), param.getPageIndex(), param.getPageSize());
        PageEntity<InviteRecordVO> result = new PageEntity<>();
        List<InviteRecordVO> list = new ArrayList<>();
        poPage.getRecords().forEach(po -> {
            InviteRecordVO vo = new InviteRecordVO();
            vo.setUserId(po.getInviterId());
            UAppUserPO userPO = uAppUserDAO.findById(po.getInviterId());
            vo.setNickName(userPO.getNickname());
            vo.setCreateTime(po.getCreateTime());
            vo.setPinecone(po.getPinecone());
            list.add(vo);
        });
        result.setList(list);
        result.setTotal(poPage.getTotal());
        return Result.success().data(result).build();
    }

    @Override
    @Transactional
    public Result<Boolean> acceptInvite(AcceptInviteDTO param) {
        AppUser currentUser = ApiContext.getCurrentUser();
        UAppUserPO my = uAppUserDAO.findById(currentUser.getUserId());
        if (Objects.nonNull(my.getInviterId())) {
            return Result.failure().message("已经存在邀请者").build();
        }
        UAppUserPO userPO = uAppUserDAO.findOne(UAppUserPO::getInviterCode, param.getInviterCode());
        if (Objects.isNull(userPO)) {
            return Result.failure().message("邀请码不存在").build();
        }
        my.setInviterId(userPO.getId());
        my.setInviterDate(LocalDate.now());
        uAppUserDAO.updateById(my);
        if (baseUtilService.checkInvite()) {
            MConfPrizePO prizePO = mConfPrizeDAO.findOne(MConfPrizePO::getAction, PrizeActionEnum.invite.getCode());
            uAppUserEquityDAO.addPinecone(my.getId(), prizePO.getInvitedPinecone());
            uAppUserEquityDAO.addPinecone(userPO.getId(), prizePO.getInvitationPinecone());
            DDetailsPineconePO myDetail = new DDetailsPineconePO();
            myDetail.setUserId(my.getId());
            myDetail.setLabelType(LabelTypeEnum.accept_invite.getCode());
            myDetail.setDetailsType(DetailsTypeEnum.income.getCode());
            myDetail.setPinecone(prizePO.getInvitedPinecone());
            dDetailsPineconeDAO.save(myDetail);
            DDetailsPineconePO inviteDetail = new DDetailsPineconePO();
            inviteDetail.setUserId(userPO.getId());
            inviteDetail.setLabelType(LabelTypeEnum.invite_friends.getCode());
            inviteDetail.setInviterId(my.getId());
            inviteDetail.setDetailsType(DetailsTypeEnum.income.getCode());
            inviteDetail.setPinecone(prizePO.getInvitationPinecone());
            dDetailsPineconeDAO.save(inviteDetail);
        }
        return Result.success().data(Boolean.TRUE).build();
    }

    @Override
    public void downloadInviteImage(HttpServletResponse response) throws IOException, FontFormatException {
        AppUser currentUser = ApiContext.getCurrentUser();
        UAppUserPO userPO = uAppUserDAO.findById(currentUser.getUserId());
        // 清空response
        response.reset();
        // 设置response的Header
        response.addHeader("Content-Disposition", "attachment;filename=" + userPO.getInviterCode() + ".png");
        response.setContentType("application/octet-stream");
        Color color = new Color(128, 17, 23);
        ImageUtils.addTextToImage(myAppConfig.getInviteImagePath(), userPO.getInviterCode(), response.getOutputStream(), color, 60, 555, 1694);
    }

}
